<?php
namespace app\back\controller;
use Qiniu\Auth;
use think\Controller;
use think\Request;
use think\Db;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager; 
class Banner extends Common
{   
	//轮播图列表
    public function index()
    {   
      
    	//获取banner数据
    	$data = Db::name('ads')->select();
    	$this->assign('data',$data);

       return $this->fetch('Banner/index'); 
    }
    //新增轮播图页面展示  
    public function creat()
    {
 		 return $this->fetch('Banner/creat');
     }
     //添加内容
     public function add_banner()
    {
      require_once VENDOR_PATH.'qiniu\php-sdk\autoload.php';
      $banner_title = input('title');//广告标题
      $status = is_null(request()->input('status')) ? 1 : request()->input('status');
    	$file = request()->file('img');
    	 if($file!==null){           
            // 要上传图片的本地路径
            $filePath = $file->getRealPath();
            $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
            // 上传到七牛后保存的文件名
            $key =substr(md5($file->getRealPath()) , 0, 5). date('YmdHis') . rand(0, 9999) . '.' . $ext;
            $accessKey = 'hBsaU5bQNuUTXT90seIdCIUIBDCG-43_TB_fBkzC';
            $secretKey = '5dbXwTehAI75xPDjorbdXat4hL6L39-_OFIR7m6Y';
            $auth=new Auth($accessKey,$secretKey);
            // 要上传的空间
            $bucket = "banner";
            //空间域名
            $domain = config('DOMAIN');
            $token = $auth->uploadToken($bucket);
            // 初始化 UploadManager 对象并进行文件的上传
            $uploadMgr = new UploadManager();
            // 调用 UploadManager 的 putFile 方法进行文件的上传
            list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
            if ($err !== null) {
                return ["err"=>1,"msg"=>$err,"data"=>""];
            } else {
                //返回图片的完整URL
              $arr = array (
                  'adName' => $banner_title,
                  'adFile' => $domain . $ret['key'],
                  'adStatus' => $status,
                  'adStartDate'=>date("Y-m-d H:i:s")
                );
              $data=Db::name('ads')->insert($arr);
              if($data){
               return json(['state' => '1', 'msg' => '添加成功!']);
                }else{
                   return json(['state' => '0', 'msg' => '添加失败，请刷新页面!']);
                }
            }
    	}
    }
  public function edit()
    {
      $id = input('id');
     // echo $id;die;
      $adsList = Db::name('ads')->where("adId",$id)->find();
      $this->assign('adsList',$adsList);
      return $this->fetch('Banner/edit');
    }
   //修改内容
  	public function save()
  	{
  		$adId = input('adId');
      //echo $adId;
  		$adName = input('title');
      $banner_img = substr(input('banner_img'),33);
  		$file = request()->file('img');
      //echo $file;die;
  		if($file==null){
    		$arr = array(
    		'adId' => $adId,
    		'adName' => $adName,
    		);
    		$data=Db::name('ads')->where("adId",$adId)->update($arr);
                if($data){
                     return json(['state' => '1', 'msg' => '修改成功!']);
                }else{
                  return json(['state'=>'0','msg'=>'你未改动数据!']);
                }
    	}else{
            // 要上传图片的本地路径
            $filePath = $file->getRealPath();
            $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
            // 上传到七牛后保存的文件名
            $key =substr(md5($file->getRealPath()) , 0, 5). date('YmdHis') . rand(0, 9999) . '.' . $ext;
            require_once VENDOR_PATH.'qiniu/php-sdk/autoload.php';
            // 构建鉴权对象
            $auth = new Auth();
            // 要上传的空间
            $bucket = "banner";
            $domain = config('DOMAIN');//域名
            $token = $auth->uploadToken($bucket);
            // 初始化 UploadManager 对象并进行文件的上传
            $uploadMgr = new UploadManager();
             // 初始化 BucketManager 对象并进行文件的删除
            $deleteBuc = new BucketManager($auth);
            // 调用 BucketManager 的 delete 方法进行文件的删除
            $deleteBuc->delete($bucket, $banner_img);
            // 调用 UploadManager 的 putFile 方法进行文件的上传
            list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
            if ($err !== null) {
                return json(['state' => '0', 'msg' => '上传图片失败!']);
            } else {
                //返回图片的完整URL
                // return json(["err"=>0,"msg"=>"上传完成","data"=>$domain . $ret['key']]);
              $arr = array (
                  'adName' => $adName,
                  'adFile' => $domain . $ret['key']
                );
              $data=Db::name('ads')->where("adId",$adId)->update($arr);
              if($data){
               return json(['state' => '1', 'msg' => '修改成功!']);
                }else{
                  return json(['state' => '0', 'msg' => '修改失败再试试!']);
                }
            }
    	   }
  	}
  	// //单个删除banner
  	 public function del_banner()
  	{
  		$adId = input('adId');
      $data = Db::name('ads')->where('adId',$adId)->find();
      //print_r($data);die;
  		$banner_img = substr($data['adFile'],33);
     // print_r($banner_img);die;
      require_once VENDOR_PATH.'qiniu/php-sdk/autoload.php';
        // 构建鉴权对象
        $auth = new Auth();
         // 要上传的空间
        $bucket ='banner';
         $domain = config('DOMAIN');
        // 初始化 BucketManager 对象并进行文件的删除
        $deleteBuc = new BucketManager($auth);
        // 调用 BucketManager 的 delete 方法进行文件的删除
        list($ret, $err)= $deleteBuc->delete($bucket, $banner_img);
        if($err == null){
            $list = Db::name('ads')->where("adId",$adId)->delete();
            if($list){
                 return json(['state' => '1', 'msg' => '删除成功!']);
            }else{
                return json(['state' => '0', 'msg' => '删除失败再试试!']);
            }
        }
  	}
}